-include config.mak

TARGET = $(ARCH)-$(OS)-$(ABI)
LLVM_ROOT = $(shell realpath $(OHOS_ROOT))/prebuilts/clang/ohos/linux-x86_64/llvm
CC = "$(LLVM_ROOT)/bin/clang --target=$(TARGET)"
CXX = "$(LLVM_ROOT)/bin/clang++ --target=$(TARGET)"
AR = $(LLVM_ROOT)/bin/llvm-ar
RANLIB = $(LLVM_ROOT)/bin/llvm-ranlib
STRIP = $(LLVM_ROOT)/bin/llvm-strip
LIBCC = $(shell echo $(CC) -print-libgcc-file-name | sh)

DST_DIR = $(shell realpath ./cross)_$(ARCH)_$(OS)_$(ABI)

SYS_LIB_DIR = /system/lib

MUSL_SRC_DIR = musl_ohos_src
MUSL_CNF = CC=$(CC) CXX=$(CXX) AR=$(AR) RANLIB=$(RANLIB) LIBCC=$(LIBCC) \
			--prefix=$(DST_DIR) --target=$(TARGET) --syslibdir=$(SYS_LIB_DIR)

all: musl_make

musl_make : musl_src
	cd $(MUSL_SRC_DIR) && ./configure $(MUSL_CNF) &&  $(MAKE) -j && $(MAKE) install

%-clang: tools/%-clang.in
	sed -e 's!@CC@!$(CC)!g' -e 's!@PREFIX@!$(shell realpath $(DST_DIR))!g' -e 's!@INCDIR@!$(shell realpath $(DST_DIR)/include)!g' \
		-e 's!@LIBDIR@!$(shell realpath $(DST_DIR)/lib)!g' -e 's!@LDSO@!$(SYS_LIB_DIR)/ld-musl-arm.so.1!g' $< > $@
	chmod +x $@
	mv -f $@  $(DST_DIR)/bin/$@

wrapper_make : musl_make ld.musl-clang musl-clang

musl_src :
	$(shell $(OHOS_ROOT)/third_party/musl/scripts/porting.sh -i $(OHOS_ROOT)/third_party/musl -o $(MUSL_SRC_DIR) -p linux)

print-% :
	@echo $* = $($*)

clean:
	rm -rf $(MUSL_SRC_DIR) $(DST_DIR) ld.musl-clang musl-clang
